package com.wbao.dianniu.ui;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.timchat.utils.ChatActivity;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.UserInfoHolder;
import com.wbao.dianniu.adapter.WorkExperienceAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.JobDetailData;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.listener.IJobCollectListener;
import com.wbao.dianniu.listener.IJobDetailListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.JobCollectManager;
import com.wbao.dianniu.manager.JobDetailManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 个人简历
 *
 * @author yejianjun
 */
public class JobDetailsActivity extends BaseActivity implements IJobDetailListener, IJobCollectListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private JobDetailManager manager;
    private TextView tv_jobName;
    //    private LinearLayout layout_head;
//    private ImageView iv_head;
//    private TextView tv_iv_name;
//    private TextView tv_label;
//    private ImageView sexIV;
//    private ImageView addV;
    private TextView tv_money;
    private TextView tv_trial;
    private TextView tv_trial_ruel;
    private TextView tv_place;
    private TextView tv_years;
    private TextView tv_education;
    private MyListView mListView;
    private int jobId;
    private JobDetailData data;
    private Button applyButton;
    private Button shareBtn;
    private TextView btn_jubao;
    private Dialog dialog;
    private ImageView ivCalled, ivSendMsg, ivCollect;
    private JobCollectManager collectManger;
    private WorkExperienceAdapter adapter;
    private List<WorkExperienceData> experienceList;
    //    private UserInfoHolder userInfoHolder;
    private ScrollView scrollView;
    private ImageView headIV;
    private TextView nameTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.job_details, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.resume));
        initWattingView();
        init();
        initData();
        data = new JobDetailData();
        manager = new JobDetailManager(this);
        manager.addJobDetailListener(this);
        collectManger = new JobCollectManager(this);
        collectManger.addJobCollectListener(this);

        Intent intent = getIntent();
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            jobId = Integer.valueOf(id);
        } else {
            jobId = intent.getIntExtra(Const.INTENT_JOB_ID, 0);
        }
        manager.jobDetail(jobId, GlobalContext.getAccountId());
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void init() {
        scrollView = findViewById(R.id.job_detail_scrollview);
        tv_jobName = findViewById(R.id.job_name);
        /*userInfoHolder = new UserInfoHolder();
        userInfoHolder.headInfoLayout = findViewById(R.id.user_head_layout);
        userInfoHolder.headIV = findViewById(R.id.user_head);
        userInfoHolder.nameTV = findViewById(R.id.user_name);
        userInfoHolder.labelTV = findViewById(R.id.user_label);
        userInfoHolder.sexIV = findViewById(R.id.user_sex);
        userInfoHolder.partnerIV = findViewById(R.id.user_partner);
        userInfoHolder.addV = findViewById(R.id.add_v_iv);*/
        headIV = findViewById(R.id.include_head_iv);
        nameTV = findViewById(R.id.include_name_tv);
        tv_money = findViewById(R.id.job_money);
        tv_trial = findViewById(R.id.job_is_trial);
        tv_trial_ruel = findViewById(R.id.job_trial_ruel);
        tv_place = findViewById(R.id.job_place);
        tv_years = findViewById(R.id.job_years);
        tv_education = findViewById(R.id.job_education);
        mListView = findViewById(R.id.job_detail_listview);
        btn_jubao = findViewById(R.id.job_jubao);
        applyButton = findViewById(R.id.job_apply);
        ivCalled = findViewById(R.id.jobCalled);
        ivSendMsg = findViewById(R.id.jobSendMsg);
        ivCollect = findViewById(R.id.jobCollect);
//        userInfoHolder.headInfoLayout.setOnClickListener(this);
        btn_jubao.setOnClickListener(this);
        tv_trial_ruel.setOnClickListener(this);
        ivCalled.setOnClickListener(this);
        ivSendMsg.setOnClickListener(this);
        applyButton.setOnClickListener(this);
        ivCollect.setOnClickListener(this);

        shareBtn = getRightTextButton();
        shareBtn.setText(getResources().getString(R.string.share));
        shareBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                // 调用分享内容
                String imageUrl;
                if (TextUtils.isEmpty(data.getHeadPic())) {
                    imageUrl = GlobalContext.cdndownUrl + "logo.png";
                } else {
                    imageUrl = GlobalContext.cdndownUrl + data.getHeadPic();
                }
                String content = "应聘岗位：" + data.getPost() + "\n" + "工作经验：" + data.getExperience();
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(JobDetailsActivity.this, content, 4, imageUrl, data.getId());
            }
        });

    }

    private void initData() {
        experienceList = new ArrayList<WorkExperienceData>();
        adapter = new WorkExperienceAdapter(this, 1);
        mListView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(mListView);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.job_apply:        // 邀请面试
                if (GlobalContext.getAccountId() == data.getUserInfo().accountId) {
                    Notification.toast(this, "亲，不能邀请自己哦");
                    return;
                }
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                if (!GlobalContext.getIndustryAuthority()) {
                    showIndustryAuth(getResources().getString(R.string.incomplete_industry_auth));
                    return;
                }
                Intent invitedIntent = new Intent();
                invitedIntent.putExtra(Const.INTENT_JOB_ID, data.getId());
                invitedIntent.setClass(JobDetailsActivity.this, JobInviteActivity.class);
                startActivity(invitedIntent);
                break;
            /*case R.id.user_head_layout://点击头像
                ActivityUtils.intoHeadInfoActivity(data.getId(), JobDetailsActivity.this);
                break;*/
            case R.id.job_jubao:    //举报
                ActivityUtils.intoReportActivity(JobDetailsActivity.this, ReportType.TYPE_JOB, jobId);
                break;
            /*case R.id.right_button:    //分享
                // 调用分享内容
                String imageUrl;
                if (TextUtils.isEmpty(data.getHeadPic())) {
                    imageUrl = GlobalContext.cdndownUrl + "logo.png";
                } else {
                    imageUrl = GlobalContext.cdndownUrl + data.getHeadPic();
                }
                String content = "应聘岗位：" + data.getPost() + "\n" + "工作经验：" + data.getExperience();
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(this, content, 4, imageUrl, data.getId());
                break;*/
            case R.id.job_trial_ruel:    //规则
                Intent intent = new Intent();
                intent.setClass(JobDetailsActivity.this, TrialRuelActivity.class);
                startActivity(intent);
                break;
            case R.id.jobCalled:
                String mobile = data.getMobile();
                // 打电话
                if (TextUtils.isEmpty(mobile)) {
                    if (null != data.getUserInfo()) {
                        mobile = data.getUserInfo().mobile;
                    }
                }
                callDialog(mobile);
                break;
            case R.id.jobCollect:
                if (1 == data.getIscollect()) {
                    data.setIscollect(0);
                    ivCollect.setImageResource(R.drawable.collection_icon);
                    Notification.toast(JobDetailsActivity.this, "已取消收藏");
                } else {
                    data.setIscollect(1);
                    ivCollect.setImageResource(R.drawable.collected_icon);
                    Notification.toast(JobDetailsActivity.this, "已收藏");
                }
                collectManger.jobCollect(GlobalContext.getAccountId(), jobId);
                break;
            case R.id.jobSendMsg:    // 跳转到聊天窗口
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                //跳转到聊天界面
                GlobalUserData userData = new GlobalUserData();
                ChatActivity.navToChat(this, userData.getEnvironemt() + String.valueOf(data.getUserInfo().accountId), TIMConversationType.C2C,GlobalContext.cdndownUrl +  data.getUserInfo().headPic, data.getUserInfo().realName, GlobalContext.cdndownUrl + GlobalContext.getHeadPic());
                break;
            default:
                break;
        }
    }

    /**
     * 显示行业认证弹出框
     */
    private void showIndustryAuth(String msg) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        Window win = dialog.getWindow();
        win.getDecorView().setPadding(3, 3, 3, 3);
        win.setGravity(Gravity.CENTER);
        View view = LayoutInflater.from(this).inflate(R.layout.custom_message_dialog, null);
        Button okBtn = view.findViewById(R.id.custom_msg_ok);
        Button cancelBtn = view.findViewById(R.id.custom_msg_cancel);
        TextView message = view.findViewById(R.id.custom_msg_message);
        message.setText(msg);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        okBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                // 跳转到行业认证界面
                Intent intent = new Intent();
                intent.setClass(JobDetailsActivity.this, IndustryAuthActivity.class);
                startActivity(intent);
            }
        });
        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }


    /**
     * 拨打电话
     */
    private void callDialog(final String mobile) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle(mobile);
        builder.setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                PermissionUtils.getInstance().intentToCall(JobDetailsActivity.this, mobile);
            }
        });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }


    @Override
    public void onJobDetailFailure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
//		ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
    }

    @Override
    public void onJobDetailSuccess(JobDetailData data) {
        if (null == data) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText("数据为空...");
            return;
        }
        waittingLayout.setVisibility(View.GONE);
        this.data = data;
        display(data);
        scrollView.smoothScrollTo(0, 10);
    }

    private void display(JobDetailData data) {
        tv_jobName.setText(data.getPost() == null ? "" : data.getPost());
        /*
        if (!TextUtils.isEmpty(data.getHeadPic())) {
            PictureDownloadUtils.displayHeadImage(this, userInfoHolder.headIV, data.getHeadPic());
        }
        userInfoHolder.nameTV.setText(data.getRealName() == null ? "" : data.getRealName());
        userInfoHolder.labelTV.setText(data.getLabel() == null ? "" : data.getLabel());
        Utils.showSex(this, data.getUserInfo().sex, userInfoHolder.sexIV);
        Utils.showPartner(this, data.getUserInfo().partner, userInfoHolder.partnerIV);
        Utils.showAuth(data.getUserInfo(), userInfoHolder.addV);
        */
        if (null == data.getUserInfo()) { // 导入进去的数据
            if (null != data.getSex() && data.getSex().equals("0")) {
                headIV.setImageDrawable(getResources().getDrawable(R.drawable.head_girl_icon));
            } else {
                headIV.setImageDrawable(getResources().getDrawable(R.drawable.head_boy_icon));
            }
            nameTV.setText(data.getName() == null ? "" : data.getName());
            // 导入数据时，不允许聊天和邀请面试
            ivSendMsg.setClickable(false);
            ivSendMsg.setImageResource(R.drawable.home_main_icon_third_n);
            applyButton.setClickable(false);
            applyButton.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
        } else {
            PictureDownloadUtils.displayHeadImage(this, headIV, data.getUserInfo().headPic);
            nameTV.setText(data.getUserInfo().realName == null ? "" : data.getUserInfo().realName);
        }
        tv_money.setText(data.getSalary() == null ? "" : data.getSalary());
        tv_trial.setText(data.getTryout() == null ? "" : data.getTryout());
        tv_place.setText(data.getAddress() == null ? "" : data.getAddress());
        tv_years.setText(data.getExperience() == null ? "" : data.getExperience());
        tv_education.setText(data.getEducation() == null ? "" : data.getEducation());
        if (!TextUtils.isEmpty(data.getDescribe())) {
            experienceList = Utils.parseWorkData(data.getDescribe());
            adapter.setData(experienceList);
            setListViewHeightBasedOnChildren(mListView);
            adapter.notifyDataSetChanged();
        }
        if (1 == data.getIscollect()) {
            ivCollect.setImageResource(R.drawable.collected_icon);
        } else {
            ivCollect.setImageResource(R.drawable.collection_icon);
        }

    }

    @Override
    public void onJobCollectFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onJobCollectSuccess() {
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter   
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目   
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高   
            listItem.measure(0, 0);
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeJobDetailListener(this);
        }
        if (null != collectManger) {
            collectManger.removeJobCollectListener(this);
        }
    }
}
